<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <el-card class="box-card" v-if="crud.optPageShow.listPage">
        <div slot="header" class="clearfix">
          <span>Agent列表</span>
        </div>
        <!--工具栏-->
        <div class="head-container">
          <crudOperation :permission="permission"/>
        </div>
        <!--表格渲染-->
        <el-table border stripe ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;"
                  @select="crud.selectChange" @select-all="crud.selectAllChange"
                  @selection-change="crud.selectionChangeHandler"
                  @filter-change="crud.handleFilterChange" @row-dblclick="toDetail"
                  :header-cell-style="{background:'#eef1f6',color:'#606266'}">
          <el-table-column type="selection"/>
          <el-table-column v-if="columns.visible('agentCode')" prop="agentCode" min-width="150px" label="Agent编码"/>
          <el-table-column v-if="columns.visible('agentName')" prop="agentName" min-width="150px" label="Agent名称"/>
          <el-table-column v-if="columns.visible('agentIp')" :show-overflow-tooltip="true" prop="agentIp"
                           label="Agent主机"/>
          <el-table-column v-if="columns.visible('agentPort')" prop="agentPort" label="AGENT端口"/>
          <el-table-column v-if="columns.visible('serverAccount')" prop="serverAccount" label="SSH用户"/>
          <el-table-column v-if="columns.visible('serverPort')" prop="serverPort" label="SSH端口"/>

          <el-table-column v-if="columns.visible('agentStatus')" label="状态"
                           prop="agentStatus"
                           key="agentStatus"
                           :filters="[{ text: '未发布', value: '0' }, { text: '正常', value: '1' }, { text: '停用', value: '2' }]"
                           :filter-method="filterAgentStatus"
                           filter-placement="bottom-end" :filter-multiple="false" column-key="agentStatus">
            <template slot-scope="scope">
              <el-tag size="small" v-if="scope.row.agentStatus=='1'" align="center" type="success"
                      style="width:60px;">正常
              </el-tag>
              <el-tag size="small" v-if="scope.row.agentStatus=='0'" align="center" type="info"
                      style="width:60px;">未发布
              </el-tag>
              <el-tag size="small" v-if="scope.row.agentStatus=='2'" align="center" type="warning"
                      style="width:60px;">停用
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('upUser')" prop="upUser" label="修改人"/>
          <el-table-column v-if="columns.visible('upTs')" prop="upTs" :show-overflow-tooltip="true"
                           label="最后修改时间" min-width="140">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.upTs }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="box-card" v-if="crud.optPageShow.addPage">
        <div slot="header" class="clearfix">
          <div class="el-page-header">
            <div class="el-page-header__left" @click="crud.goBack">
              <i class="el-icon-back"></i>
              <div class="el-page-header__title">返回</div>
            </div>
            <div class="el-page-header__content" style="font-size: 14px;">Agent编辑</div>
          </div>
        </div>
        <div class="dataFrom">
          <el-form ref="form" :rules="rules" label-position="left" label-width="240px" :model="form">
            <div>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="Agent名称" prop="agentName">
                    <el-input v-model="form.agentName" v-bind:disabled="form.pkId" maxlength="12"
                              show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      Agent名称不多于12位，且不可重复
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="Agent主机" prop="agentIp">
                    <el-input v-model="form.agentIp" v-bind:disabled="form.pkId&&form.agentStatus=='1'"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      Agent的主机地址(格式 xx.xx.xx.xx,例如:192.168.1.1)
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="Agent端口" prop="agentPort">
                    <el-input v-model="form.agentPort" v-bind:disabled="form.pkId&&form.agentStatus=='1'" maxlength="5"
                              show-word-limit/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      不能多于5个字符
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="SSH用户名" prop="serverAccount">
                    <el-input v-model="form.serverAccount"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      用于AGENT自动化部署和启停
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="SSH密码" prop="serverPwd">
                    <el-input v-model="form.serverPwd" type="password" auto-complete="off"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      用于AGENT自动化部署和启停
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="SSH端口" prop="serverPort">
                    <el-input v-model="form.serverPort" type="serverPort" maxlength="5"
                              show-word-limit/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      用于AGENT自动化部署和启停
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="安装路径" prop="remoteInstallPath">
                    <el-input v-model="form.remoteInstallPath" v-bind:disabled="form.pkId&&form.agentStatus=='1'"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      远程服务器安装AGENT的路径
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="服务器版本" prop="serverVer">
                    <el-input v-model="form.serverVer" v-bind:disabled="form.pkId&&form.agentStatus=='1'"/>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      服务器操作系统版本号
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>

              <el-row>
                <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="节点描述" prop="agentDesc">
                    <!--  <el-input v-model="form.agentDesc"/>-->
                    <el-input type="textarea" :rows="2"
                              placeholder="请输入内容"
                              v-model="form.agentDesc" v-bind:disabled="form.pkId&&form.agentStatus=='1'">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="9" class="data_from_el-col">
                  <div class="hex-form-inf">
                    <div class="hex-form-inf-content">
                      节点的特殊信息描述备注
                    </div>
                    <i
                      class="el-icon-info hex-form-inf-icon"
                      @click="onOperInf($event)"
                      data-status="off"
                    ></i>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <div class="form-operator-button">
                  <el-button @click="crud.goBack()" type="primary">取消</el-button>
                  <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU()">保存</el-button>
                  <el-button v-if="form.pkId === null" type="primary" @click="saveAndInstall">保存并发布</el-button>
                </div>
              </el-row>
            </div>
          </el-form>
        </div>
      </el-card>
      <agent-info v-if="crud.optPageShow.detailPage" :init="init" :agentInfo="agentInfo"/>
    </div>
  </div>
</template>
<script>
import agentApi from '@/api/agent/agent'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import crudOperation from '@crud/extend/agent/manageAgent/CRUD.operation'
import agentInfo from './agentInfo'
import {mapGetters} from 'vuex'
import {validateHostCallBack, validatePort} from '@/utils/validate'
import {encrypt, decrypt} from '@/utils/rsaEncrypt'

//默认去查询
const queryList = [{'cloumValue': 'agentCode', 'cloumName': 'Agent编码'}, {
  'cloumValue': 'agentName',
  'cloumName': 'Agent名称'
}]
const defaultCrud = CRUD({
  title: 'AGENT管理',
  url: '/api/agentInf/selectPages',
  queryList: queryList,
  sort: 'sort,asc',
  crudMethod: {...agentApi}
})
const defaultForm = {
  pkId: null,
  agentCode: null,
  agentName: null,
  agentDesc: null,
  agentIp: null,
  agentPort: 80,
  agentStatus: null,
  agentHaStatus: null,
  serverVer: null,
  serverAccount: null,
  serverPwd: null,
  remoteInstallPath: '/opt/hex-agent',
  serverPort: 22,
  crtUser: null,
  upUser: null
}

export default {
  name: 'agent',
  components: {crudOperation, agentInfo},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['AGENT_STATUS'],
  data() {
    var validateAgentName = (rule, value, callback) => {
      if (value != null && value != '') {
        agentApi.checkAgentName(this.crud.form).then(res => {
          if (res === false) {
            callback(new Error('AGENT名称已存在!'));
          } else {
            callback();
          }
        });
      } else {
        callback();
      }
    }
    var validateAgentHostExist = (rule, value, callback) => {
      if (validateHostCallBack(value)) {
        agentApi.checkAgentHost(this.crud.form).then(res => {
          if (res === false) {
            callback(new Error('AGENT主机已存在!'));
          } else {
            callback();
          }
        });
      } else {
        callback(new Error('请输入正确的主机地址!'));
      }

    }
    return {
      agentInfo: null,
      editSHHPassword: '',
      permission: {
        add: ['agent:add'],
        edit: ['agent:edit'],
        del: ['agent:del'],
        install: ['agent:install'],
        start: ['agent:start'],
        stop: ['agent:stop'],
        restart: ['agent:restart']
      },
      rules: {
        agentName: [
          {required: true, message: '请输入AGENT名称', trigger: 'blur'},
          {validator: validateAgentName, trigger: 'blur'}
        ],
        agentIp: [
          {required: true, message: '请输入AGENT主机', trigger: 'blur'},
          {validator: validateAgentHostExist, trigger: 'blur'}
        ],
        agentPort: [
          {required: true, message: '请输入AGENT端口号', trigger: 'blur'},
          {validator: validatePort, trigger: 'blur'}
        ],
        serverAccount: [
          {required: true, message: '请输入SSH用户名', trigger: 'blur'},
        ],
        serverPwd: [
          {required: true, message: '请输入SSH密码', trigger: 'blur'},
        ],
        serverPort: [
          {required: true, message: '请输入SSH端口', trigger: 'blur'},
          {validator: validatePort, trigger: 'blur'},
        ],
        remoteInstallPath: [
          {required: true, message: '请输入AGENT安装路径', trigger: 'blur'},
        ],
      },
    }

  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.init();
  },
  methods: {
    // 提交前
    [CRUD.HOOK.beforeSubmit]() {
      if (this.crud.form.serverPwd != this.editSHHPassword) {
        this.crud.form.serverPwd = encrypt(this.crud.form.serverPwd)
      }
      this.crud.form.crtUser = this.user.username;
      this.crud.form.upUser = this.user.username;
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.editSHHPassword = form.serverPwd;
    },
    init() {
      this.crud.goBack();
    },
    filterAgentStatus(value, row) {
      return row.agentStatus === value;
    },
    toDetail(row, column, event) {
      this.agentInfo = row;
      this.crud.toDetail();
    },
    onOperInf: function (e) {
      let status = e.target.getAttribute('data-status');
      let previousNode = e.target.previousElementSibling;
      if ("off" == status) {
        previousNode.setAttribute('class', 'hex-form-inf-content-show');
        e.target.setAttribute('data-status', 'on');
      } else {
        previousNode.setAttribute('class', 'hex-form-inf-content');
        e.target.setAttribute('data-status', 'off');
      }
    },
    saveAndInstall() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '拼命安装中......',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.crud.form.crtUser = this.user.username;
          this.crud.form.upUser = this.user.username;
          this.crud.form.serverPwd = encrypt(this.crud.form.serverPwd)
          agentApi.saveAndInstall(this.crud.form).then(res => {
            loading.close();
            this.crud.goBack()
            this.crud.toQuery()
            this.crud.notify('安装成功', CRUD.NOTIFICATION_TYPE.SUCCESS);
          }).catch(() => {
            loading.close();
          })
        } else {
          return false;
        }
      });

    }
  }
}
</script>
<style scoped>
.dashboard-editor-container {
  padding: 18px 22px 22px 22px;
  background-color: rgb(240, 242, 245);
  margin-bottom: 80px;
}

.form-operator-button {
  padding: 10px;
  background-color: #fff;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0;
  bottom: 33px;
  height: 64px;
  line-height: 44px;
  text-align: center;
}

.hex-form-inf {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  cursor: pointer;
  margin-right: 40px;
  position: relative;
  min-height: 33px;
  margin-left: 60px;
  line-height: 33px;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}

.hex-form-inf .hex-form-inf-content-show {
  padding: 0 4%;
  background-color: gainsboro;
  border-radius: 8px;
}

.hex-form-inf-icon {
  font-size: 20px;
  margin-top: 5px;
  position: absolute;
  right: 0px;
}

</style>
